<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class SyncShowdoc extends Command
{
    protected $signature = 'sync:showdoc';

    protected $description = '使用 showdoc 开放API, 扫描API文档目录, 同步API文档';

    protected const API_URL = 'https://www.showdoc.cc/server/api/item/updateByApi';

    protected $http;

    protected $api_key;

    protected $api_token;

    public function __construct()
    {
        parent::__construct();
        $this->http = new \GuzzleHttp\Client();
        $this->api_key =  config('services.showdoc.key');
        $this->api_token = config('services.showdoc.token');
    }

    /**
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException|\Exception
     */
    public function handle()
    {
        $allFiles = File::allFiles(base_path('docs'));
        foreach ($allFiles as $file) {
            if ($file->getExtension() !== 'md') continue;
            // 更新时间超过半小时
            if ((time() - $file->getATime()) > 1800) continue;

            $catname = mb_convert_encoding($file->getRelativePath(), 'utf-8');
            $title = str_replace('.md', '', $file->getFilename());
            $content = File::get($file->getPathname());
            $this->uploadToShowdoc($catname, $title, $content);
        }
    }

    /**
     * 上传到 Showdoc
     * @param $catname
     * @param $title
     * @param $content
     * @throws \Exception
     */
    protected function uploadToShowdoc($catname, $title, $content)
    {
        $data = [
            'api_key' => $this->api_key,
            'api_token' => $this->api_token,
            'cat_name' => $catname,
            'page_title' => $title,
            'page_content' => $content,
        ];
        $response = $this->http->post(self::API_URL, [
            'verify' => false,// 禁用ssl证书校验
            'form_params' => $data,
        ]);
        $response = json_decode((string)$response->getBody());
        if ($response->error_code) {
            throw new \Exception("{$response->error_code}: {$response->error_message}");
        }
        $this->info(mb_convert_encoding("{$catname}/{$title} 上传成功", 'gb2312'));
    }
}
